package com.example.stmall.manager.service.impl;

import com.example.stmall.manager.entity.Goods;
import com.example.stmall.manager.entity.GoodsPic;
import com.example.stmall.manager.mapper.GoodsMapper;
import com.example.stmall.manager.service.GoodsPicService;
import com.example.stmall.manager.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    //注入GoodsPic的Service层对象
    @Autowired
    private GoodsPicService goodsPicService;

    @Override
    /**
     * 开启Spring的事务管理
     */
    @Transactional(isolation = Isolation.SERIALIZABLE,  //ACID  隔离性
                    propagation= Propagation.REQUIRED,  //传播机制 7个
                    rollbackFor = Exception.class)  //回归：当方法中
    public int add(Goods goods) throws Exception {
        //1.验证参数
        //2.业务逻辑的处理
        //3.访问数据库

        //只会保存商品的数据，还要保存商品的图片
        //1.先保存商品，获取数据库自动生成的ID主键
        int code = goodsMapper.insert(goods);

        if(code > 0){
            //2.再保存图片，需要用到商品的ID
            for (GoodsPic pic : goods.getPics()) {
                pic.setGoodsId(goods.getId());
            }
            goodsPicService.addPatch(goods.getPics());
        }
        //图片的数据在goods里面
        return code;
    }

    @Override
    public int remove(Integer id) throws Exception {
        Goods goods = goodsMapper.selectById(id);
        if(goods == null){
            throw  new Exception("ID不存在！");
        }
        //只删除Goods，不删除图片
        return goodsMapper.delete(id);
    }

    @Override
    public int edit(Goods goods) throws Exception {
        Goods sGoods = goodsMapper.selectById(goods.getId());
        if(sGoods == null){
            throw new Exception("ID不存在！");
        }
        //只修改了Goods，没有修改图片
        return goodsMapper.update(goods);
    }

    @Override
    public Goods getById(Integer id) throws Exception {
        Goods goods = goodsMapper.selectById(id);
        if(goods == null){
            throw new Exception("ID不存在");
        }
        return goods;
    }

    @Override
    public List<Goods> search(Goods goods) {
        return goodsMapper.select(goods);
    }

    @Override
    public PageInfo searchByPage(Integer page, Integer limit, Goods goods) {
        //1.启动分页查询
        PageHelper.startPage(page,limit);
        //2.调用Mapper层
        List<Goods> list = goodsMapper.select(goods);
        //3.构造PageInfo对象
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
